/*
 * Copyright (C) 2015 MC
 * All rights reserved.
 *
 * $$File: $$
 * $$DateTime: $$
 * $$Author: $$
 * $$Revision: $$
 */

package com.glela.api.upload.qiniu.impl;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glela.api.upload.qiniu.IUploadObject;
import com.glela.api.upload.qiniu.http.HttpProtocolHandler;
import com.glela.api.upload.qiniu.http.HttpRequest;
import com.glela.api.upload.qiniu.http.HttpResponse;
import com.glela.api.upload.qiniu.http.HttpResultType;
import com.glela.api.upload.util.Base64;
import com.glela.api.upload.util.FopParse;
import com.glela.api.upload.util.FopParse.Item;
import com.glela.api.upload.util.ImageProperties;
import com.glela.api.upload.util.UpLoadConfig;
import com.glela.api.upload.util.VideoProperties;
import com.glela.api.upload.util.qryTask;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
//import com.squareup.okhttp.OkHttpClient;
//import com.squareup.okhttp.Request;
//import com.squareup.okhttp.Response;
/**
 * @author 
 */
@Service("uploadObject")
public class UploadObject implements IUploadObject
{

	private static class GeneratorRandom
	{

		private static char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
				'u', 'v', 'w', 'x', 'y', 'z', '0', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'Y', 'X', 'W',
				'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'K', 'J', 'H', 'G', 'F', 'E', 'Z' };

		public static String genratorRandomPwd()
		{
			return GeneratorRandom.genratorRandomString(6);
		}

		public static String genratorRandomString(int length)
		{
			StringBuilder pwd = new StringBuilder("");
			Random r = new Random();
			for (int i = 0; i < length; i++) {
				int x = Math.abs(r.nextInt(str.length));
				pwd.append(str[x]);
			}
			return pwd.toString();
		}

	}

	private static final Logger logger = Logger.getLogger(UploadObject.class);

	/**
	 * @param id
	 *            七牛视频和视频截图的列表ID
	 * @throws Exception
	 * @throws HttpException
	 * @return
	 */
	@Override
	public Map<String, Object> getQNInfoHttpMessage(String id) throws HttpException, Exception
	{

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", false);
		VideoProperties videoProperties = new VideoProperties();
		List<ImageProperties> imageList = new ArrayList<ImageProperties>();
		logger.info("put media image to Qiniu result >> " + id);
		//通过HTTPGET请求获取该ID下的视频和视频截图信息
		HttpRequest request = new HttpRequest(HttpResultType.STRING);
		//设置格式码
		request.setCharset("utf-8");
		//设置超时时间
		request.setConnectionTimeout(3000);
		//get类型提交
		request.setMethod("GET");
		//设置请求的参数ID
		request.setQueryString("id=" + id);
		//查询七牛的URL
		request.setUrl(UpLoadConfig.httpTask);
		HttpResponse response = HttpProtocolHandler.getInstance().execute(request);

		logger.info("get Result  message:==>" + response.getStringResult());
		//请求是否成功
		if (response.isSucced()) {
			String jsonResult = response.getStringResult();
			JSONObject result = JSON.parseObject(jsonResult);

			//当返回状态为处理成功或者为等待处理时
			if ("0".equals(result.getString("code"))) {
//				List<Item> list = new FopParse(UpLoadConfig.httpBase).parse(jsonResult);
				JSONObject obj = JSON.parseObject(jsonResult);
				JSONArray items = obj.getJSONArray("items");
				//				ItemOne itemOne = (ItemOne) items.get(0);
				JSONObject itemOne = (JSONObject) items.get(0);
				JSONObject itemTwo = (JSONObject) items.get(1);
				videoProperties.setVideoPath(itemOne.getString("key"));
				videoProperties.setKey(id);

				String images = itemTwo.getString("keys");
				images = images.substring(1, images.length() - 1);
				String[] is = images.split(",");

				for (String element : is) {
					ImageProperties imageProperties = new ImageProperties();
					element = element.substring(1, element.length() - 1);
					imageProperties.setImagePath(element); //视频截图路径
					imageList.add(imageProperties);
				}

				resMap.put("videoProperties", videoProperties);
				resMap.put("imageProperties", imageList);
				resMap.put("success", true);

			}
			else {
				resMap.put("success", false);
			}

		}

		return resMap;

	}

	/**
	 * 上传截图
	 * 
	 * @param name
	 *            七牛保存的文件名称
	 * @param bitRate
	 *            码率
	 * @param width
	 *            宽
	 * @param height
	 *            高
	 * @return
	 * @throws Exception
	 * @throws HttpException
	 */
	@Override
	public Map<String, Object> pfopVideo(String name, String bitRate, String width, String height, String videoType)
	{
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);
		OperationManager operater = new OperationManager(auth);

		Map<String, Object> resMap = new HashMap<String, Object>();
		StringBuilder fops = new StringBuilder(256);
		fops.append("avthumb/" + videoType + "/aspect/16:9"); //设置播放器中显示的宽高比
		fops.append("/vb/" + bitRate + ";"); //设置码率
		//		for (int i = 2; i < 22; i += 2) {
		//			fops.append("vsample/jpg/offset/"); //设置截图的宽和高
		//			fops.append(i);
		//			fops.append("/w/" + width + "/h/" + height + ";");
		//		}

		//		vsample/jpg/ss/7/t/600/s/480x360/pattern

		String base64Pwd = Base64.encoderBase64((name + "_$(count).jpg").getBytes());
		//		Base64.en

		fops.append("vsample/jpg/ss/1/interval/6/t/43/s/" + width + "x" + height + "/pattern/" + base64Pwd + ";"); //设置截图的宽和高
		logger.info("转码传参："+fops.toString());
		StringMap params = new StringMap().putNotEmpty("notifyURL", UpLoadConfig.callbackUrl)
				.putNotEmpty("bucket", UpLoadConfig.bucket).putNotEmpty("key", name).putNotEmpty("fops", fops.toString())
				.putNotEmpty("force", "1").put("pipeline", "liujie");

		try {

			//获取视频信息在七牛中的ID
			String id = operater.pfop(UpLoadConfig.bucket, name, fops.toString(), params);
			//通过HTTP  get请求QN的信息
			if (!StringUtils.isNullOrEmpty(id)) {

				//			resMap = getQNInfoHttpMessage(width, height, id);
				resMap.put("QNId", id);
				resMap.put("success", true);
				return resMap;
			}
			else {
				resMap.put("success", false);
				return resMap;
			}

		}
		catch (QiniuException e) {
			Response r = e.response;
			logger.error(r.toString());
			e.printStackTrace();
			try {
				logger.error(r.bodyString());
				resMap.put("success", false);
				return resMap;
			}
			catch (QiniuException e1) {
				e1.printStackTrace();
			}
			resMap.put("success", false);
			return resMap;
		}

	}

	/* (non-Javadoc)
	 * @see com.glela.common.api.upload.IUploadObject#uploadImage(byte[], java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, Object> uploadImage(byte[] mediaContent, String width, String height)
	{
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);
		//实例化七牛
		UploadManager uploadManager = new UploadManager();
		//通过bucket获取token
		String token = auth.uploadToken(UpLoadConfig.bucket);
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmmss");
		String key = sdf.format(new Date()) + GeneratorRandom.genratorRandomString(5);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//开始上传视频
			Response response = uploadManager.put(mediaContent, key, token);
			logger.info("put media to Qiniu result >> " + response.toString());
			// 处理截图
			if (response.isOK()) {
				ImageProperties imagePropertie = response.jsonToObject(ImageProperties.class);

				try {
					resMap = pfopImage(auth, key, width, height, imagePropertie);
					if (resMap != null) {

						return resMap;
					}
					else {

						return null;
					}
				}
				catch (HttpException e) {
					e.printStackTrace();
				}
				catch (Exception e) {
					e.printStackTrace();
				}

			}

			return null;
		}
		catch (QiniuException e) {
			e.printStackTrace();
		}

		return null;
	}

	/* (non-Javadoc)
	 * @see com.glela.common.api.upload.IUploadObject#uploadVideo(byte[], java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String, Object> uploadVideo(byte[] mediaContent)
	{
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);
		//实例化七牛
		UploadManager uploadManager = new UploadManager();
		//通过bucket获取token
		String token = auth.uploadToken(UpLoadConfig.bucket);
		//		logger.debug("生成TOKEN:" + token);
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmmss");
		String key = sdf.format(new Date()) + GeneratorRandom.genratorRandomString(5);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//开始上传视频
			Response response = uploadManager.put(mediaContent, key, token);
			logger.info("put media to Qiniu result >> " + response.toString());
			// 处理截图
			if (response.isOK()) {
				VideoProperties videoProperties = response.jsonToObject(VideoProperties.class);

				//					resMap = pfopVideo(auth, key, bitRate, width, height, videoProperties);
				resMap.put("videoProperties", videoProperties);
				return resMap;

			}
			else {

				return null;
			}

		}
		catch (QiniuException e) {
			e.printStackTrace();
			return null;
		}

	}
	
	@Override
	public Map<String, Object> uploadVideo(File file) {
		Auth auth = Auth.create(UpLoadConfig.accessKey, UpLoadConfig.secretKey);
		//实例化七牛
		UploadManager uploadManager = new UploadManager();
		//通过bucket获取token
		String token = auth.uploadToken(UpLoadConfig.bucket);
		//		logger.debug("生成TOKEN:" + token);
		SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmmss");
		String key = sdf.format(new Date()) + GeneratorRandom.genratorRandomString(5);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			//开始上传视频
			Response response = uploadManager.put(file, key, token);
			logger.info("put media to Qiniu result >> " + response.toString());
			// 处理截图
			if (response.isOK()) {
				VideoProperties videoProperties = response.jsonToObject(VideoProperties.class);

				//					resMap = pfopVideo(auth, key, bitRate, width, height, videoProperties);
				resMap.put("videoProperties", videoProperties);
				return resMap;

			}
			else {

				return null;
			}

		}
		catch (QiniuException e) {
			e.printStackTrace();
			return null;
		}
	}

	private Map<String, Object> pfopImage(Auth auth, String name, String width, String height, ImageProperties imagePropertie)
			throws HttpException, Exception
	{
		OperationManager operater = new OperationManager(auth);
		JSONObject result = null;
		ImageProperties imageProperties = new ImageProperties();
		Map<String, Object> resMap = new HashMap<String, Object>();
		StringBuilder fops = new StringBuilder(256);

		fops.append("imageView2/1/w/" + width + "/h/" + height + ";"); //设置播放器中显示的宽高比

		StringMap params = new StringMap().putNotEmpty("notifyURL", UpLoadConfig.callbackUrl)
				.putNotEmpty("bucket", UpLoadConfig.bucket).putNotEmpty("key", name).putNotEmpty("fops", fops.toString())
				.putNotEmpty("force", "1").put("pipeline", "liujie");

		try {

			//获取视频信息在七牛中的ID
			String id = operater.pfop(UpLoadConfig.bucket, name, fops.toString(), params);
			//通过HTTPGET请求获取该ID下的视频和视频截图信息
			HttpRequest request = new HttpRequest(HttpResultType.STRING);
			//设置格式码
			request.setCharset("utf-8");
			//设置超时时间
			request.setConnectionTimeout(60000);
			//get类型提交
			request.setMethod("GET");
			//设置请求的参数ID
			request.setQueryString("id=" + id);
			//查询七牛的URL
			request.setUrl(UpLoadConfig.httpTask);
			//执行请求
			ExecutorService executor = Executors.newCachedThreadPool();
			qryTask task = new qryTask(request);
			Future<HttpResponse> tt = executor.submit(task);
			HttpResponse response = tt.get();
			executor.shutdown();

			//请求是否成功
			if (response.isSucced()) {
				String jsonResult = response.getStringResult();
				result = JSON.parseObject(jsonResult);
				if ("0".equals(result.getString("code")) || "3".equals(result.getString("code"))) {
					List<Item> list = new FopParse(UpLoadConfig.httpBase).parse(jsonResult);
					for (Item i : list) {
						//判断是否为视频
						if (i.isMp3()) {

							continue;
						}
						else {
							//否则为图片，这里图片先设置一张
							imageProperties.setImagePath(i.getKey()); //视频截图路径
							imageProperties.setHeight(height);
							imageProperties.setWidth(width);
							break;
						}
					}
					result.put("success", true);
					result.put("items", list);
				}
				else {
					result.put("success", false);
				}
			}

			logger.info("put media image to Qiniu result >> " + id);

			//设置图片信息的BEAN  并返回

			resMap.put("imageProperties", imageProperties);
			return resMap;
		}
		catch (QiniuException e) {
			Response r = e.response;
			logger.error(r.toString());
			e.printStackTrace();
			try {
				logger.error(r.bodyString());
				return null;
			}
			catch (QiniuException e1) {
				e1.printStackTrace();
			}
			return null;
		}

	}
	
	
	
	
	/**
	 * @param id
	 *            七牛视频相关详细信息
	 * @throws Exception
	 * @throws HttpException
	 * @return
	 */
	@Override
	public Map<String, Object> getVideoInfoHttpMessage(String videoPath) throws HttpException, Exception
	{

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", false);
//		VideoProperties videoProperties = new VideoProperties();
//		List<ImageProperties> imageList = new ArrayList<ImageProperties>();
		logger.info("put media image to Qiniu result >> " + videoPath);
		//通过HTTPGET请求获取该ID下的视频和视频截图信息
		HttpRequest request = new HttpRequest(HttpResultType.STRING);
		//设置格式码
		request.setCharset("utf-8");
		request.setHead("Content-Type", "application/x-www-form-urlecnoded");

		//设置超时时间
		request.setConnectionTimeout(3000);
		//get类型提交
		request.setMethod("GET");
		//设置请求的参数ID
//		request.setQueryString("id=" + id);
		//查询七牛的URL
		request.setUrl(UpLoadConfig.httpBase+videoPath+"?avinfo");
		HttpResponse response = HttpProtocolHandler.getInstance().execute(request);
		logger.info("get Result  message:==>" + response.getStringResult().getBytes("utf-8"));
		//请求是否成功
		if (response.isSucced()) {
//			String jsonResult = new String(response.body().bytes()));
				JSONObject obj = JSON.parseObject(new String(response.getByteResult()));
				JSONObject videoInfo = obj.getJSONObject("format");
				//				ItemOne itemOne = (ItemOne) items.get(0);
				
				//获取视频时间
				String videoTime=videoInfo.getString("duration");
				//将时间转换为时分秒
				//获取时间（单位秒）
				Double vsTime=Double.parseDouble(videoTime);
				BigDecimal   b   =   new   BigDecimal(vsTime);  
				vsTime=   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
				Double vmTime= vsTime/60;
				String videoTimeStr="";
				//拼接分钟
				if (vmTime>1) {
					videoTimeStr=videoTimeStr+Math.floor(vmTime);
				}
				if (vmTime<10) {
					videoTimeStr="0"+videoTimeStr;
				}
				//得到秒数
				 vsTime=(vmTime-Math.floor(vmTime))*60;
				 //秒数保留整数，四舍五入
				 vsTime=(double) Math.round(vsTime); 
				 if (vsTime>10) {
					 videoTimeStr=videoTimeStr+":0"+vsTime;
				}else if (vsTime>0&&vsTime<10) {
					 videoTimeStr=videoTimeStr+":"+vsTime;
				}
				
				 //获取double类型的时间保留小数后两位
				 resMap.put("doubleTime", new   BigDecimal( Double.parseDouble(videoTime)).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()     );
				 resMap.put("FrmatTime", videoTimeStr);
				 
				
				resMap.put("success", true);

			}
			else {
				resMap.put("success", false);
			}

		
//
//		OkHttpClient client = new OkHttpClient();
//
//        Request request1 = new Request.Builder()
//                .url(YtUpLoadConfig.httpBase+videoPath+"?avinfo")
//                .addHeader("Content-Type", "application/x-www-form-urlecnoded")
//                .build();
//        try {
//            Response response1 = client.newCall(request1).execute();
//            System.out.println("StatusCode is " + response.code());
//            System.out.println(response.headers().toString());
//            System.out.println(new String(response.body().bytes()));
//        } catch (IOException e) {
//            System.out.println(e.toString());
//        }
    

		
		
		
		
		
		return resMap;

	}

	@Override
	public Map<String, Object> getVideoInfoHttpMessage1(String videoPath)
			throws HttpException, Exception {
		
		
		
		
		return  null;
	}

}
